'use strict';
const {
	Model
} = require('sequelize');
const bcrypt = require('bcrypt')
module.exports = (sequelize, DataTypes) => {
	class User extends Model {
		/**
		 * Helper method for defining associations.
		 * This method is not a part of Sequelize lifecycle.
		 * The `models/index` file will call this method automatically.
		 */
		static associate(models) {
			// define association here
		}
	}

	User.init({
			email: {
				type: DataTypes.STRING,
				allowNull: false,
				validate: {
					notNull: {msg: '邮箱必须存在'},
					notEmpty: {msg: '邮箱不能为空'},
					isEmail: {msg: '邮箱格式有误'},
					async isUnique(value) {
						const user = await User.findOne({where: {email: value}})
						if (user) throw new Error('邮箱已存在')
					}
				}
			},
			username: {
				type: DataTypes.STRING,
				allowNull: false,
				validate: {
					notNull: {msg: '账号必须存在'},
					notEmpty: {msg: '账号不能为空'},
					len: {args: [2, 45], msg: '账号长度需要在2~45之间'},
					async isUnique(value) {
						const user = await User.findOne({where: {username: value}})
						if (user) throw new Error('账号已存在')
					}
				}
			},
			password: {
				type: DataTypes.STRING,
				allowNull: false,
				validate: {
					notNull: {msg: '密码必须存在'},
					notEmpty: {msg: '密码不能为空'}
				},
				set(value) {
					if (value.length >= 8 && value.length <= 36) {
						this.setDataValue('password',bcrypt.hashSync(value, 10))
					} else {
						throw new Error('密码长度需要在8~36位之间')
					}
				}
			},
			nickname: {
				type: DataTypes.STRING,
				allowNull: false,
				validate: {
					notNull: {msg: '昵称必须存在'},
					notEmpty: {msg: '昵称不能为空'},
					len: {args: [2, 45], msg: '昵称长度需要在2~45之间'}
				}
			},
			sex: {
				type: DataTypes.TINYINT,
				allowNull: false,
				validate: {
					notNull: {msg: '性别必须存在'},
					notEmpty: {msg: '性别不能为空'},
					isIn: {args: [[0, 1, 2]], msg: '性别值必须是：0男性，1女性，2未知'}
				}
			},
			company: DataTypes.STRING,
			introduce: DataTypes.TEXT,
			role: {
				type: DataTypes.TINYINT,
				allowNull: false,
				validate: {
					notNull: {msg: '用户组必须存在'},
					notEmpty: {msg: '用户组不能为空'},
					isIn: {args: [[0, 100]], msg: '性别值必须是：0用户，100超管'}
				}
			},
			avatar: {
				type: DataTypes.STRING,
				allowNull: true,
				validate: {
					isUrl: {msg: '图片地址不正确'},
				}
			}
		},
		{
			sequelize,
			modelName:
				'User',
		});
	return User;
};